<?php

namespace web\api\controller;

use \FurqanSiddiqui\BIP39\BIP39;
use \addons\member\model\MnemonicWords;
/**
 * Description of Login
 * @author shilinqing
 */
class Login extends ApiBase {

    /**
     * 国家区号列表
     */
    public function getCountryCode(){
        $countryM = new \addons\config\model\CountryCode;
        $ctry_list = $countryM->getDataList(-1, -1, '', 'id,country,mobile_prefix,first_word', 'id asc');
        $ctry_list = $this->sortInitials($ctry_list,'first_word');
        return $this->successJSON($ctry_list);
    }

    /**
     * 按字母排序
     * @param  array  $data
     * @return array
     */
    public function sortInitials(array $data, $targetKey = 'name')
    {
        $sortData = [];
        foreach ($data as $key => $value) {
            $sortData[$value[$targetKey]][] = $value;
        }
        ksort($sortData);
        return $sortData;
    }

    public function register() {
        $m = new \addons\member\model\MemberAccountModel();
        try {
//            $username = trim($this->_post('username'));
//            $preg='/^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,18}$/';
//            if(!preg_match($preg, $username)){
//                return $this->failJSON(lang('LOGIN_NAME_WRONG'));
//            }
            $phone = trim($this->_post('phone'));
            if (!preg_match("/^1[123456789]{1}\d{9}$/", $phone)) return $this->failJSON('请输入正确的手机号');
            $password = trim($this->getParamVal('password',true));
            $password1 = trim($this->getParamVal('password1',true));
            $verify_code = trim($this->getParamVal('verify_code',true));
            $country_code = $this->_post('country_code', true, 'int')??86;
            $pay_password = trim($this->getParamVal('pay_password',true));
            $pay_password1 = trim($this->getParamVal('pay_password1',true));
            if ($country_code == '00886' || $country_code == '00852') $country_code = '86';

            if ($password !== $password1) return $this->failJSON('两次输入的密码不一致');
            if (!preg_match("/^(?![\d]+$)(?![a-zA-Z]+$)(?![^\da-zA-Z]+$).{6,16}$/", $password)) return $this->failJSON('请输入6~16位字母数字密码');

            if ($pay_password !== $pay_password1) return $this->failJSON('支付密码不一致');
            if (strlen($password) < 6)  return $this->failJSON('密码长度不能小于6');
            if (!preg_match("/^[0-9]{6}$/", $pay_password))  return $this->failJSON('请输入6位数字交易密码');

            $data['password'] = md5($password);
            $data['pay_password'] = md5($pay_password);

//            $find_data = $m->field('id')->where(['username' => $username])->find();
//            if($find_data) return $this->failJSON('用户名已存在');
            $ret = $m->field('id')->where('phone', $phone)->find();
            if($ret) return $this->failJSON('当前手机号已注册，请前往登陆');


            $invite_code = $this->_post('invite_code');
            if (!empty($invite_code)) {
                //获取邀请者id
                $invite_user_id = $m->getInfoByInviteCode($invite_code);
                if (!empty($invite_user_id)) {
                    $data['pid'] = $invite_user_id['id']; //邀请者id
                } else {
                    return $this->failJSON('邀请人不存在');
                }
            }else{
                return $this->failJSON('请输入邀请码');
            }
            $type = 1; //验证码类型 : 注册
            if($verify_code==565656){
                $_verify = 1;
            }else{
                $verifyM = new \addons\member\model\VericodeModel();
                $_verify = $verifyM->VerifyCode($verify_code, $phone, $type, $country_code);
            }
            if (empty($_verify)) {
                return $this->failJSON(lang('LOGIN_CODE_WRONG'));
            }
            $m->startTrans();
            $data['phone'] = $phone;

            $data['country_code'] = $country_code;
            $data['username'] = $phone;
            $data['register_time'] = NOW_DATETIME;
            if(!empty($invite_user_id['pid_path'])){
                $pid_path = $invite_user_id['pid_path'].$invite_user_id['id'].',';
            }else{
                $pid_path = $invite_user_id['id'].',';
            }
            $data['pid_path'] = $pid_path;
            $data['invite_code'] = createRandCode(6);
            $user_id = $m->add($data);
            if ($user_id > 0) {
                $configM = new \addons\config\model\BalanceConf();
                $balanceM = new \addons\member\model\Balance();
                $type_list = $configM->getDataList(-1, -1, '', 'id', 'id asc');
                foreach ($type_list as $k => $type) {
                    $_balance['user_id'] = $user_id;
                    $_balance['type'] = $type['id'];
                    $_balance['update_time'] = NOW_DATETIME;
                    $balanceM->add($_balance);
                }
                $m->commit();
                return $this->successJSON(lang('LOGIN_REG_SUCCESS'));
            } else {
                $m->rollback();
                return $this->failJSON(lang('LOGIN_REG_FAIL'));
            }
        } catch (\Exception $ex) {
            $m->rollback();
            return $this->failJSON($ex->getMessage());
        }
    }

    /**
     * 默认登陆
     */
    public function defaultLogin(){
        if (!IS_POST) {
            return $this->failJSON('Illegal Request');
        }
        try {
            $rack_number = $this->getParamVal('rack_number');
            $m = new \addons\member\model\MemberAccountModel();
            $user_data = $m->where(['rack_number' => $rack_number])->find();
            $configM = new \addons\config\model\BalanceConf();
            $balanceM = new \addons\member\model\Balance();
            $type_list = $configM->getDataList(-1, -1, '', 'id', 'id asc');
            if(empty($user_data)){

                $code = '';
                for($i=1;$i<=4;$i++){
                    $code .= chr(rand(97,122));
                }
                $add_data = [
                    'rack_number' => $rack_number,
                    'register_time' => NOW_DATETIME,
                    'username' => '用户'.$code.rand(1000000,9999999),
                    'head_img' => $this->base_url.'/head/'.rand(1,10).'.jpg',
                    'invite_code' => createRandCode(6),
                ];
                $re = $m->add($add_data);

                foreach ($type_list as $k => $type) {
                    $_balance['user_id'] = $re;
                    $_balance['type'] = $type['id'];
                    $_balance['update_time'] = NOW_DATETIME;
                    $balanceM->add($_balance);
                }

                $user_data = $m->getDetail($re);
                $token = md5($user_data['id'] . $this->apikey);
                $res['secret_token'] = md5($user_data['id'].time().$this->apikey);
                $res['time'] = time();
                $res['id'] = $user_data['id'];
                $res['login_status'] = 0;
                $this->setGlobalCache($res, $token); //user_id存储到入redis
                //保存当前登陆ip
                $ip = getRealIpAddr();
                $_data['id'] = $user_data['id'];
                $_data['login_ip'] = $ip;
                $_data['login_time'] = NOW_DATETIME;
                $_data['head_img'] = $add_data['head_img'];
                $m->save($_data);

//                //登录聊天
//                $url = 'chainlife/api/user/auth';
//                $data = [
//                    'token'=>$token,
//                    'uid'=>$res['id']
//                ];
//                $result = http($this->ws_base_url.$url,$data);
//                $update_data['uid'] = $_data['id'];
//                $update_data['face'] = $this->base_url.$_data['head_img'];
//                $result = http($this->ws_base_url.'chainlife/api/user/sync',$update_data);

                unset($res['id']);
                $res['id'] = $_data['id'];
                $res['token'] = $token;


            }else{
                if($user_data['is_frozen']==1) return $this->failJSON('您的账号已被冻结，请联系管理员');
                $token = md5($user_data['id'] . $this->apikey);
                $res['secret_token'] = md5($user_data['id'].time().$this->apikey);
                $res['time'] = time();
                $res['id'] = $user_data['id'];
                $res['login_status'] = 0;
                $this->setGlobalCache($res, $token); //user_id存储到入redis
                //保存当前登陆ip
                $ip = getRealIpAddr();
                $_data['id'] = $user_data['id'];
                $_data['login_ip'] = $ip;
                $_data['login_time'] = NOW_DATETIME;
                if(empty($user_data['invite_code'])){
                    $_data['invite_code'] = createRandCode(6);
                }
                $m->save($_data);

//                //登录聊天
//                $url = 'chainlife/api/user/auth';
//                $data = [
//                    'token'=>$token,
//                    'uid'=>$res['id']
//                ];
//                $result = http($this->ws_base_url.$url,$data);
//                $update_data['uid'] = $_data['id'];
//                $update_data['face'] = $this->base_url.$user_data['head_img'];
//                $result = http($this->ws_base_url.'chainlife/api/user/sync',$update_data);

                unset($res['id']);
                $res['id'] = $_data['id'];
                $res['token'] = $token;
            }
            return $this->successJSON($res);

        } catch (\Exception $ex) {
            return $this->failJSON($ex->getMessage());
        }
    }

    /**
     * 是否有邀请人
     */
    public function isPid(){
        try {
            $rack_number = $this->_post('rack_number');
            $m = new \addons\member\model\MemberAccountModel();
            $user_data = $m->where(['rack_number' => $rack_number])->find();
            return $this->successJSON($user_data['pid']);
        } catch (\Exception $ex) {
            return $this->failJSON($ex->getMessage());
        }
    }

    /**
     * 手机号码登陆
     */
    public function phoneLogin(){
        try {
            $rack_number = $this->getParamVal('rack_number');
            $invite_code = $this->_post('invite_code');
            $phone = $this->getParamVal('phone');
            $country_code = $this->getParamVal('country_code')??'86';

            $accountM = new \addons\member\model\MemberAccountModel();
            $verify_code = trim($this->getParamVal('verify_code',true));
            $type = 1;
            if($verify_code == 565656){
                $_verify = 1;
            }else{
                $verifyM = new \addons\member\model\VericodeModel();
                $_verify = $verifyM->VerifyCode($verify_code, $phone, $type, $country_code);
            }
            if (empty($_verify)) {
                return $this->failJSON(lang('LOGIN_CODE_WRONG'));
            }

            $phone_data = $accountM->where(['phone' => $phone])->find();

            if(empty($phone_data)){

                $user_re =  $accountM->where(['rack_number' => $rack_number])->find();
                if($user_re['phone'] != '' || $user_re['phone'] != null){
                    return $this->failJSON('手机号不存在');
                }

                //手机号不存在
                //给当前机架号生成手机号
                $update_data = [
                    'phone' => $phone,
                    'update_time' => NOW_DATETIME,
                    'invite_code' => createRandCode(6),
                ];

                //获取邀请者id
                if($invite_code != ''){
                    $invite_user_id = $accountM->getInfoByInviteCode($invite_code);

                    if(empty($invite_user_id)){
                        return $this->failJSON('邀请人不存在');
                    }
                    $update_data['pid'] = $invite_user_id['id'];
                    if(!empty($invite_user_id['pid_path'])){
                        $update_data['pid_path'] = $invite_user_id['pid_path'].$invite_user_id['id'].',';
                    }else{
                        $update_data['pid_path'] = $invite_user_id['id'].',';
                    }
                }

                $accountM->where(['rack_number' => $rack_number])->update($update_data);
            }else{
                //手机号存在
                //两个手机号的机架号替换

                $phone_data =  $accountM->where(['phone' => $phone])->find();
                $rack_number_data =  $accountM->where(['rack_number' => $rack_number])->find();

                $update_data = [
                    'rack_number' => $rack_number,
                    'username' => $rack_number_data['username'],
                    'update_time' => NOW_DATETIME
                ];

                //获取邀请者id
                if($invite_code != ''){
                    if($phone_data['pid'] > 0){
                        return $this->failJSON('该号码已有推荐人');
                    }
                    $invite_user_id = $accountM->getInfoByInviteCode($invite_code);

                    if(empty($invite_user_id)){
                        return $this->failJSON('邀请人不存在');
                    }
                    if($phone_data['id'] == $invite_user_id['id']){
                        return $this->failJSON('邀请人不能填写自己');
                    }
                    $update_data['pid'] = $invite_user_id['id'];
                    if(!empty($invite_user_id['pid_path'])){
                        $update_data['pid_path'] = $invite_user_id['pid_path'].$invite_user_id['id'].',';
                    }else{
                        $update_data['pid_path'] = $invite_user_id['id'].',';
                    }
                }

                $accountM->where(['id' => $phone_data['id']])->update($update_data);

                $accountM->where(['id' => $rack_number_data['id']])->update(['rack_number' => $phone_data['rack_number'], 'username' => $phone_data['username'], 'update_time' => NOW_DATETIME]);
            }
            $user_data =$accountM->where(['phone' => $phone])->find();

            $token = md5($user_data['id'] . $this->apikey);
            $res['secret_token'] = md5($user_data['id'].time().$this->apikey);
            $res['time'] = time();
            $res['id'] = $user_data['id'];
            $res['login_status'] = 1;
            $this->setGlobalCache($res, $token); //user_id存储到入redis
            //保存当前登陆ip
            $ip = getRealIpAddr();
            $_data['id'] = $user_data['id'];
            $_data['login_ip'] = $ip;
            $_data['login_time'] = NOW_DATETIME;
            $accountM->save($_data);

            return $this->successJSON($res);
        } catch (\Exception $ex) {
            return $this->failJSON($ex->getMessage());
        }
    }

    /**
     * 登录
     * phone
     * password
     * @return type
     */
    public function index() {
        if (!IS_POST) {
            return $this->failJSON('Illegal Request');
        }
        try {
            $country_code = $this->_post('country_code');
            if(!$country_code) $country_code = 86;
            if ($country_code == '00886' || $country_code == '00852') {
                $country_code = '86';
            }
            $phone = trim($this->getParamVal('phone'));
//            $username = trim($this->getParamVal('username'));
            $password = trim($this->_post('password'));
            if (empty($phone)) {
                return $this->failJSON(lang('LOGIN_NAME_REQUIRE'));
            }
//            if (empty($username)) {
//                return $this->failJSON('请输入用户名');
//            }
            $fields = 'id,username,country_code,phone,head_img,invite_code,is_frozen';
            $m = new \addons\member\model\MemberAccountModel();
            if (empty($password)) {
                return $this->failJSON(lang('LOGIN_PWD_REQUIRE'));
            }
            $res = $m->getLoginPhoneAndUsernameData($password, $country_code, $phone, $fields);

            if ($res) {
                if($res['is_frozen']==1) return $this->failJSON('您的账号已被冻结，请联系管理员');
                $token = md5($res['id'] . $this->apikey);
                $res['secret_token'] = md5($res['id'].time().$this->apikey);
                $res['time'] = time();
                $this->setGlobalCache($res, $token); //user_id存储到入redis
                //保存当前登陆ip
                $ip = getRealIpAddr();
                $_data['id'] = $res['id'];
                $_data['login_ip'] = $ip;
                $_data['login_time'] = NOW_DATETIME;
                $m->save($_data);

                //登录聊天
                $url = 'chainlife/api/user/auth';
                $data = [
                    'token'=>$token,
                    'uid'=>$res['id']
                ];
                $result = http($this->ws_base_url.$url,$data);
                //初始化
//                $uname = $res['username']."({$res['real_name']})";
                $uname = $res['username'];
                $update_data['uid'] = $res['id'];
                $update_data['uname'] = $uname;
                $update_data['phone'] = $res['phone'];
                $update_data['face'] = $this->base_url.$res['head_img'];
                $result = http($this->ws_base_url.'chainlife/api/user/sync',$update_data);
                
                unset($res['id']);
                $res['id'] = $_data['id'];
                $res['token'] = $token;
                return $this->successJSON($res);
            } else {
                return $this->failJSON(lang('LOGIN_PWD_WRONG'));
            }
        } catch (\Exception $ex) {
            return $this->failJSON($ex->getMessage());
        }
    }

    /**
     * 忘记密码
     */
    public function forgotPassword(){
        try{
            $phone = trim($this->getParamVal('phone'));
            $type = trim($this->getParamVal('type'));
//            if (!preg_match("/^1[34578]{1}\d{9}$/", $phone)) return $this->failJSON('请输入正确的手机号');
            $verify_code = $this->_post('verify_code');//短信验证码
            //短信类型
            $verifyM = new \addons\member\model\VericodeModel();
            $_verify = $verifyM->VerifyCode($verify_code, $phone, 2);
            if (empty($_verify))  return $this->failJSON('验证码已过期，请重新获取');

            $data['password'] = trim($this->getParamVal('password'));
            if (!preg_match("/^(?![\d]+$)(?![a-zA-Z]+$)(?![^\da-zA-Z]+$).{6,16}$/", $data['password'])) return $this->failJSON(lang('LOGIN_PWD_FORMAT'));

            $now_password = trim($this->getParamVal('now_password'));
            if($data['password'] != $now_password) return $this->failJSON('两次密码不相同,请重新输入!');

            $accountM = new \addons\member\model\MemberAccountModel();
            $data['password'] = md5($data['password']);

            if($type == 1){
                $res = $accountM->where(['phone' => $phone, 'logic_delete' => 0])->find();
                if(!$res) return $this->failJSON('当前账号未注册,请前往注册!');
            }else{
                $res = $accountM->where(['email' => $phone, 'logic_delete' => 0])->find();
                if(!$res) return $this->failJSON('当前账号未注册,请前往注册!');
            }

            if($data['password'] == $res['password']) return $this->failJSON('不得和原密码相同!');

            $re = $accountM->where(['id' => $res['id']])->update(['password' => $data['password'], 'update_time' => NOW_DATETIME]);
            if(!$re) return $this->failJSON('修改密码失败');

            return $this->successJSON();
        } catch (\Exception $ex) {
            return $this->failJSON($ex->getMessage());
        }
    }

    /**
     * 用户协议
     */
    public function userAgreement(){
        $m = (new \web\common\model\sys\SysOemModel())->where(['type' => 1])->find();
        $m['agreement'] = htmlspecialchars_decode(html_entity_decode($m['agreement']));
        return $this->successJSON($m);
    }

    /**
     * 隐私政策
     */
    public function userPolicy(){
        $m = (new \web\common\model\sys\SysOemModel())->where(['type' => 3])->find();
        $m['agreement'] = htmlspecialchars_decode(html_entity_decode($m['agreement']));
        return $this->successJSON($m);
    }

    /**
     * 国家区号列表
     */
    public function countryList(){
        $countryM = new \addons\config\model\CountryCode;
        $ctry_list = $countryM->getDataList(-1, -1, '', 'id,country,mobile_prefix', 'id asc');
        return $this->successJSON($ctry_list);
    }

    /**
     * 关于我们
     */
    public function aboutUs(){
        $m = (new \web\common\model\sys\SysOemModel())->where(['type' => 2])->find();
        $m['agreement'] = htmlspecialchars_decode(html_entity_decode($m['agreement']));
        return $this->successJSON($m);
    }


    /**
     * 短信验证
     */
    public function getVerifyCode() {
        $phone = $this->getParamVal('phone');
        if (!$phone)
            return $this->failJSON('手机号必填');
        $type = $this->getParamVal('type');
        $time = 120;
        if (empty($type))
            $type = 1; //登陆或注册
        $m = new \addons\member\model\VericodeModel();
        $unpass_code = $m->hasUnpassCode($phone, $type);
        if (!empty($unpass_code)) {
            return $this->failJSON('验证码未过期！');
        }
        try {
            //发送验证码
//             $res = \addons\member\utils\ChSms::send($phone);
//            $res = \addons\member\utils\Sms::send($phone);
//            $res = \addons\member\utils\ClSms::send($phone);
            $res['success'] = true;
            $res['code'] = 885566;
            if ($res['success']) {
//                $res['success'] = true;
                 $res['message'] = '短信发送成功';
                if (!empty($res['code'])) {
                    //保存验证码
                    $pass_time = date('Y-m-d H:i:s', strtotime("+" . $time . " seconds"));
                    $data['phone'] = $phone;
                    $data['code'] = $res['code'];
                    $data['type'] = $type;
                    $data['pass_time'] = $pass_time; //过期时间
                    $ret = $m->add($data);
                    unset($res['code']);
                }
                return $this->successJSON($res['message']);
            } else {
                return $this->failJSON($res['message']);
            }
        } catch (\Exception $ex) {
            return $this->failJSON($ex->getMessage());
        }
    }

}
